
package View.Cadastros;

import Model.UsuarioModel;
import Repositories.UsuarioRepository;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.netbeans.lib.awtextra.AbsoluteLayout;

/**
 *
 * @author Yanne
 */
public class ListaUsuario extends javax.swing.JDialog {

    UsuarioRepository usuarioRepository = new UsuarioRepository();
    DefaultTableModel model = new DefaultTableModel(new Object[][]{}, new Object[]{"Código", "Nome", "Login"}){
            public boolean isCellEditable(int rowIndex, int mColIndex) {  
                return false;  
            }  
        };  

    /** Creates new form ListaUsuario */
    public ListaUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
       this.setResizable(false);
        initComponents();

        AbsoluteLayout laiout = null;
        jp_lista_user.setLayout(laiout);

        //bg login
        JLabel labelLogin = new JLabel(new ImageIcon("./img/bg_lista_user.png"));
        jp_lista_user.add(labelLogin);
        labelLogin.setBounds(0, 0, 500, 390);

        //bt NOVO USUARIO listauser
        JLabel label4 = new JLabel(new ImageIcon("./img/bt_novo_usuario.png"));
        bt_Novo.add(label4);
        bt_Novo.setContentAreaFilled(false);
        bt_Novo.setBorderPainted(false);
        bt_Novo.setToolTipText("Novo Usuário [Ctrl + N]");
        
        //bt ALTERAR uauario
        JLabel label5 = new JLabel(new ImageIcon("./img/bt_alterar_usuario.png"));
        btnAlterar.add(label5);
        btnAlterar.setContentAreaFilled(false);
        btnAlterar.setBorderPainted(false);
        btnAlterar.setToolTipText("Alterar Usuário [Ctrl + A]");
       
        //bt remover  uauario
        JLabel label6 = new JLabel(new ImageIcon("./img/bt_del_usuario.png"));
        btnExcluir.add(label6);
        btnExcluir.setContentAreaFilled(false);
        btnExcluir.setBorderPainted(false);
        btnExcluir.setToolTipText("Remover Usuário [Ctrl + X]");
       
        //bt fechar listauser
        JLabel label3 = new JLabel(new ImageIcon("./img/bt_fechar_listauser.png"));
        bt_Sair.add(label3);
        bt_Sair.setContentAreaFilled(false);
        bt_Sair.setBorderPainted(false);
        bt_Sair.setToolTipText("Fechar [Esc]");

        this.setLocationRelativeTo(null);
        
        IniciarTabela();
    }

    private void IniciarTabela() {
        try {
            DefaultTableModel modelo = new DefaultTableModel(new Object[][]{}, new Object[]{"Código", "Nome", "Login"}){
            public boolean isCellEditable(int rowIndex, int mColIndex) {  
                return false;  
            }  
        };  

            ArrayList<UsuarioModel> usuarios = usuarioRepository.ListadeUsuarios();
            if (usuarios != null) {
                for (UsuarioModel usuario : usuarios) {
                    modelo.addRow(new Object[]{usuario.getUSUARIO_ID(), usuario.getUSUARIO_NOME(), usuario.getUSUARIO_LOGIN()});
                }

                TabelaUsuario.setModel(modelo);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    private void Busca() {
        try {

            ArrayList<UsuarioModel> usuarios = usuarioRepository.BuscaUsuario(txtPesquisa.getText());
            if (usuarios != null) {
                DefaultTableModel modelo = new DefaultTableModel(new Object[][]{}, new Object[]{"Código", "Nome", "Login"}){
            public boolean isCellEditable(int rowIndex, int mColIndex) {  
                return false;  
            }  
        };  
                for (UsuarioModel usuario : usuarios) {
                    modelo.addRow(new Object[]{usuario.getUSUARIO_ID(), usuario.getUSUARIO_NOME(), usuario.getUSUARIO_LOGIN()});
                }

                TabelaUsuario.setModel(modelo);
            } else {
                JOptionPane.showMessageDialog(null, "A pesquisa não obteve resultados! Faça outra pesquisa.");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jp_lista_user = new javax.swing.JPanel();
        bt_Sair = new javax.swing.JButton();
        btnPesquisar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TabelaUsuario = new javax.swing.JTable();
        txtPesquisa = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnExcluir = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        bt_Novo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jp_lista_user.setBackground(new java.awt.Color(255, 204, 204));
        jp_lista_user.setMinimumSize(new java.awt.Dimension(500, 390));
        jp_lista_user.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        bt_Sair.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bt_SairMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bt_SairMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                bt_SairMousePressed(evt);
            }
        });
        bt_Sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_SairActionPerformed(evt);
            }
        });
        jp_lista_user.add(bt_Sair, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 270, 150, 60));

        btnPesquisar.setText("Pesquisar");
        btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPesquisarActionPerformed(evt);
            }
        });
        jp_lista_user.add(btnPesquisar, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 130, 106, 27));

        TabelaUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}

            },
            new String [] {
                "Código", "Nome", "Login"
            }
        ));
        TabelaUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TabelaUsuarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TabelaUsuario);

        jp_lista_user.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, 480, 90));

        txtPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPesquisaActionPerformed(evt);
            }
        });
        jp_lista_user.add(txtPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 310, 32));

        jLabel1.setText("Pesquisar:");
        jp_lista_user.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 110, -1, -1));

        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });
        jp_lista_user.add(btnExcluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 20, 130, 70));

        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });
        jp_lista_user.add(btnAlterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 20, 130, 70));

        bt_Novo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bt_NovoMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bt_NovoMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                bt_NovoMousePressed(evt);
            }
        });
        bt_Novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_NovoActionPerformed(evt);
            }
        });
        jp_lista_user.add(bt_Novo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 130, 70));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jp_lista_user, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jp_lista_user, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void bt_SairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_SairActionPerformed
    this.dispose();
}//GEN-LAST:event_bt_SairActionPerformed

private void txtPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPesquisaActionPerformed
    Busca();
}//GEN-LAST:event_txtPesquisaActionPerformed

private void bt_NovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_NovoActionPerformed
    CadastroUsuario cadastroUsuario = new CadastroUsuario(this, true);
    cadastroUsuario.setVisible(true);
    IniciarTabela();

}//GEN-LAST:event_bt_NovoActionPerformed

private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
Alterar();
}//GEN-LAST:event_btnAlterarActionPerformed


private void Alterar()
{
    try
{
    Object objeto = TabelaUsuario.getValueAt(TabelaUsuario.getSelectedRow(), 0);
    int IdUsuario = Integer.parseInt(objeto.toString());

    CadastroUsuario cadastroUsuario = new CadastroUsuario(this, true, IdUsuario);
    cadastroUsuario.setVisible(true);
    IniciarTabela();
}
catch (ArrayIndexOutOfBoundsException ex)
{
    JOptionPane.showMessageDialog(null, "É necessário selecionar um usuario!");
}
catch (Exception ex)
{
    JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
    Busca();
}//GEN-LAST:event_btnPesquisarActionPerformed

private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed

    try {
        Object objeto = TabelaUsuario.getValueAt(TabelaUsuario.getSelectedRow(), 0);
            int IdUsuario = Integer.parseInt(objeto.toString());
        if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, "Confirma a exclusão desse usuário?")) {
            

            if (usuarioRepository.Deletar(IdUsuario)) {
                JOptionPane.showMessageDialog(null, "Usuário excluído com sucesso!");
                IniciarTabela();
            }
        }
    }
catch (ArrayIndexOutOfBoundsException ex)
{
    JOptionPane.showMessageDialog(null, "É necessário selecionar um produto!");
}
catch (Exception ex)
{
    JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_btnExcluirActionPerformed

//----------------FECHAR LISTAR USUARIOS
private void bt_SairMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_SairMouseEntered
   
    
}//GEN-LAST:event_bt_SairMouseEntered

private void bt_SairMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_SairMouseExited
  
    
}//GEN-LAST:event_bt_SairMouseExited

private void bt_SairMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_SairMousePressed
  
}//GEN-LAST:event_bt_SairMousePressed

//-=============NOVO USUARIO
private void bt_NovoMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_NovoMouseEntered
  
}//GEN-LAST:event_bt_NovoMouseEntered

private void bt_NovoMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_NovoMouseExited
  
}//GEN-LAST:event_bt_NovoMouseExited

private void bt_NovoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bt_NovoMousePressed
   
}//GEN-LAST:event_bt_NovoMousePressed

private void TabelaUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TabelaUsuarioMouseClicked
if (evt.getClickCount() > 1) {  
  Alterar();
} 
}//GEN-LAST:event_TabelaUsuarioMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable TabelaUsuario;
    private javax.swing.JButton bt_Novo;
    private javax.swing.JButton bt_Sair;
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jp_lista_user;
    private javax.swing.JTextField txtPesquisa;
    // End of variables declaration//GEN-END:variables
}
